/**
 * 工程名称:OMSJobExecutor
 * 文件名称:SysRefundController.java
 * 所属包:cn.rkylin.oms.sysrefund.controller
 * 创建时间:2017年9月21日下午2:54:30
 * 创建人:zhanghao
 */

package cn.rkylin.oms.sysrefund.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.rkylin.core.controller.ApolloController;
import cn.rkylin.oms.sysOrder.domain.SysOrder;
import cn.rkylin.oms.sysOrder.service.ISysOrderService;
import cn.rkylin.oms.sysOrder.vo.SysOrderVO;
import cn.rkylin.oms.sysrefund.servcie.ISysRefundService;

/**
 * 类名:SysRefundController <br/>
 * 作用: 系统退款单操作Controller. <br/>
 * 创建原因: 对外提供系统退款单相关操作. <br/>
 * 创建时间: 2017年9月21日 下午2:54:30 <br/>
 * 
 * @author zhanghao
 * @see
 */
@Controller
@RequestMapping("/sysRefundManager")
public class SysRefundController extends ApolloController {
    private static final Log logger = LogFactory.getLog(SysRefundController.class);
    /**
     * sysRefundService:系统退款单服务层.
     */
    @Autowired
    private ISysRefundService sysRefundService;
    @Autowired
    private ISysOrderService sysOrderService;

    /**
     * generateSysRefund:平台退款单进系统. <br/>
     * 系统定时调用.<br/>
     * 系统获取一定条件下的平台退款单，自动生成系统退款单.<br/>
     * 系统定时调用.<br/>
     * 此方法的业务逻辑较复杂，数据库操作较多，建议不要在循环中调用.<br/>
     *
     * @author zhanghao
     * @param paramMap
     *            控制参数Map
     * @return 执行成功或者失败的消息
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/autoGenerateSysRefund")
    public Map<String, Object> autoGenerateSysRefund(@RequestParam(value = "shopId") String shopId, Map paramMap) {
        logger.info(String.format("系统调用自动下载退款单：/sysRefundManager/autoGenerateSysRefund/%s", shopId));
        // 用于返回值的json对象
        Map<String, Object> returnMap;
        try {
            sysRefundService.downloadEcRefund(shopId, false);
            returnMap = getSuccessMap("系统调用完成");
        } catch (Exception e) {
            returnMap = getFailedMap(e.getMessage());
        }
        return returnMap;
    }

    /**
     * manualGenerateSysRefund:根据店铺Id+客户ID或者店铺ID+退款单ID获取相关平台退款单，并生成系统退款单. <br/>
     * 参考自动生成系统退款单的业务逻辑.<br/>
     *
     * @author zhanghao
     * @param shopId
     *            店铺ID
     * @param key
     *            查询值名称
     * @param value
     *            查询值
     * @return
     * @throws UnsupportedEncodingException
     */
    @ResponseBody
    @RequestMapping(value = "/manualGenerateSysRefund", method = RequestMethod.GET)
    public Map<String, Object> manualGenerateSysRefund(String shopId, String key, String value) {
        logger.info(String.format("系统调用手动下载退款单：/sysRefundManager/manualGenerateSysRefund/", shopId));
        // 用于返回值的json对象
        Map<String, Object> returnMap = null;

        try {
            String queryValue = URLDecoder.decode(value, "UTF-8");

            if ("ecRefundCode".equalsIgnoreCase(key)) {
                // 根据平台退款单号下载退款单
                sysRefundService.downloadEcRefundByEcRefundCode(shopId, queryValue, true);
                returnMap = getSuccessMap("平台退款单下载完成");
            } else if ("customerId".equalsIgnoreCase(key)) {
                // 根据客户ID下载退款单
                sysRefundService.downloadEcRefundByBuyerNick(shopId, queryValue, true);
                returnMap = getSuccessMap("平台退款单下载完成");
            } else if ("orderCode".equalsIgnoreCase(key)) {
                // 根据平台交易号下载退款单
                sysRefundService.downloadEcRefundByOrderCode(shopId, value, false);
                returnMap = getSuccessMap("平台退款单下载完成");
            }
        } catch (Exception e) {
            if(StringUtils.isNotEmpty(e.getMessage())&&(e.getMessage().contains("url")||e.getMessage().contains("客户ID"))) {
                returnMap = getFailedMap("店铺服务未开启，请联系系统管理员");
            }else {
                returnMap = getFailedMap("系统未知异常，请联系系统管理员");
            }
        }
        return returnMap;
    }

    /**
     * autoUpdateSysRefund:退款单更新. <br/>
     * 系统定时调用<br/>
     * 当监测到有退款单更新时，更新退款单相关信息.<br/>
     * 此方法为批量操作<br/>
     * 此方法的业务逻辑较复杂，数据库操作较多，建议不要在循环中调用.<br/>
     *
     * @author zhanghao
     * @param shopId
     * @param paramMap
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/autoUpdateSysRefund")
    public Map<String, Object> autoUpdateSysRefund(@RequestParam(value = "shopId") String shopId, String start, String end, Map paramMap) {
        logger.info(String.format("系统调用：/sysRefundManager/autoUpdateSysRefund/%s", shopId));
        // 用于返回值的json对象
        Map<String, Object> returnMap;
        try {
            sysRefundService.updateEcRefund(shopId, false);
            returnMap = getSuccessMap("系统调用完成");
        } catch (Exception e) {
            returnMap = getFailedMap(e.getMessage());
        }
        // 生成返回结果json串，null内容也需要返回
        return returnMap;
    }

    /**
     * lockShipOrder:锁订单测试接口. <br/>
     * 测试调用<br/>
     *
     * @author zhanghao
     * @param orderCode
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/lockShipOrder")
    public Map<String, Object> lockShipOrder(@RequestParam(value = "orderCode") String orderCode) {
        logger.info(String.format("系统调用：/sysRefundManager/lockShipOrder", orderCode));
        // 用于返回值的json对象
        Map<String, Object> returnMap = new HashMap();
        Map<String, String> sysOrderMap = new HashMap<String, String>();
        sysOrderMap.put("orderCode", orderCode);
        try {
            List<SysOrderVO> sysOrderList = sysOrderService.getSysOrderList(sysOrderMap);
            if (sysOrderList.size() > 0) {
                Map<String, String> returnMaps = sysRefundService.lockShipOrder((SysOrder) sysOrderList.get(0));
                returnMap = getSuccessMap("系统调用完成");
            }
        } catch (Exception e) {
            returnMap = getFailedMap(e.getMessage());
        }
        // 生成返回结果json串，null内容也需要返回
        return returnMap;
    }

    /**
     * getSuccessMap:获取成功消息Map. <br/>
     *
     * @author zhanghao
     * @param message
     * @return
     * @since JDK 1.6
     */
    private Map<String, Object> getSuccessMap(String message) {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        returnMap.put(JSON_RESULT, SUCCESS);
        returnMap.put(JSON_MSG, message);
        return returnMap;
    };

    /**
     * getFailedMap:获取失败消息Map. <br/>
     *
     * @author zhanghao
     * @param message
     * @return
     * @since JDK 1.6
     */
    private Map<String, Object> getFailedMap(String message) {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        returnMap.put(JSON_RESULT, FAILED);
        returnMap.put(JSON_MSG, message);
        return returnMap;
    };
}
